package com.supermarket.manage.business.homeinit.controller;

import com.supermarket.manage.common.dto.CodeStatus;
import com.supermarket.manage.common.dto.ResponseResult;
import com.supermarket.manage.common.dto.home.request.HomeInitParams;
import com.supermarket.manage.common.dto.home.response.ProfitDataDto;
import com.supermarket.manage.common.dto.home.response.TopDto;
import com.supermarket.manage.common.dto.home.response.TrendDto;
import com.supermarket.manage.common.dto.prod.response.ProductDto;
import com.supermarket.manage.common.pojo.Member;
import com.supermarket.manage.common.utils.BigDecimalUtil;
import com.supermarket.manage.provider.api.instock.InstockService;
import com.supermarket.manage.provider.api.outstock.OutstockService;
import com.supermarket.manage.provider.api.product.ProductService;
import com.supermarket.manage.provider.api.ucenter.MemberManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-03-18 15:56
 **/
@RestController
@RequestMapping("/homeinit")
@Api(value = "HomeInitController", tags = "首页数据查询接口")
public class HomeInitController {

    @Reference(version = "1.0.0")
    private InstockService instockService;

    @Reference(version = "1.0.0")
    private OutstockService outstockService;

    @Reference(version = "1.0.0")
    private MemberManageService memberManageService;

    @Reference(version = "1.0.0")
    private ProductService productService;

    @PreAuthorize("hasAuthority('/logined')")
    @PostMapping("/getProfitData")
    @ApiOperation(value = "获取销售、支出、利润数据", notes = "参数：buyerId,beginTime,endTime")
    public ResponseResult<ProfitDataDto> getProfitData(@Validated @RequestBody HomeInitParams params) {
        ProfitDataDto out = outstockService.getSales(params);
        ProfitDataDto in = instockService.getPurchases(params);
        if (out != null && in != null) {
            out.setPurchases(in.getPurchases());
            out.setSalesBack(in.getSalesBack());
            BigDecimal profit = BigDecimalUtil.subtract(
                    BigDecimalUtil.add(out.getSales(), out.getPurchasesBack()),
                    BigDecimalUtil.add(out.getPurchases(), out.getSalesBack()));
            out.setProfit(profit);
            return new ResponseResult<>(CodeStatus.OK, "查询成功", out);
        }
        return new ResponseResult<>(CodeStatus.FAIL, "查询失败");
    }

    @PreAuthorize("hasAuthority('/logined')")
    @PostMapping("/getSalesTrend")
    @ApiOperation(value = "获取销售趋势", notes = "参数：buyerId,beginTime,endTime")
    public ResponseResult<List<TrendDto>> getSalesTrend(@Validated @RequestBody HomeInitParams params) {
        List<TrendDto> result = outstockService.getSalesTrend(params);
        return new ResponseResult<>(CodeStatus.OK, "查询成功", result);
    }

    @PreAuthorize("hasAuthority('/logined')")
    @PostMapping("/getPurchaseTrend")
    @ApiOperation(value = "获取采购趋势", notes = "参数：buyerId,beginTime,endTime")
    public ResponseResult<List<TrendDto>> getPurchaseTrend(@Validated @RequestBody HomeInitParams params) {
        List<TrendDto> result = instockService.getPurchaseTrend(params);
        return new ResponseResult<>(CodeStatus.OK, "查询成功", result);
    }

    @PreAuthorize("hasAuthority('/logined')")
    @PostMapping("/getTopMember")
    @ApiOperation(value = "获取前十会员", notes = "参数：buyerId,beginTime,endTime")
    public ResponseResult<List<TopDto<String>>> getTopMember(@Validated @RequestBody HomeInitParams params) {
        List<TopDto<String>> result = outstockService.getTopMember(params);
        if (result != null) {
            Set<String> ids = new HashSet<>(10);
            result.forEach(d -> {
                ids.add(d.getObj());
            });
            if(ids.size()>0){
                List<Member> members = memberManageService.getMembersByIds(ids);
                result.forEach(d -> {
                    members.forEach(m -> {
                        if (d.getObj().equals(m.getMid())) {
                            d.setObj(m.getMphone());
                        }
                    });
                });
            }
        }
        return new ResponseResult<>(CodeStatus.OK, "查询成功", result);
    }

    @PreAuthorize("hasAuthority('/logined')")
    @PostMapping("/getTopSupplier")
    @ApiOperation(value = "获取前五供应商", notes = "参数：buyerId,beginTime,endTime")
    public ResponseResult<List<TopDto<String>>> getTopSupplier(@Validated @RequestBody HomeInitParams params) {
        List<TopDto<String>> result = instockService.getTopSupplier(params);
        return new ResponseResult<>(CodeStatus.OK, "查询成功", result);
    }

    @PreAuthorize("hasAuthority('/logined')")
    @GetMapping("/getWarnProd/{buyerId}")
    @ApiOperation(value = "获取库存预警商品", notes = "参数：buyerId")
    public ResponseResult<List<ProductDto>> getWarnProd(@PathVariable("buyerId") String buyerId) {
        List<ProductDto> productDtos = productService.getWarnProd(buyerId);
        if (productDtos == null || productDtos.size() == 0) {
            return new ResponseResult<>(CodeStatus.OK, "查询成功,无预警商品");
        }
        return new ResponseResult<>(CodeStatus.OK, "查询成功", productDtos);
    }
}
